package com.teaching.management.service.impl;

import com.teaching.management.entity.Course;
import com.teaching.management.entity.CourseSelection;
import com.teaching.management.entity.Teacher;
import com.teaching.management.repository.CourseRepository;
import com.teaching.management.repository.CourseSelectionRepository;
import com.teaching.management.repository.StudentRepository;
import com.teaching.management.repository.TeacherRepository;
import com.teaching.management.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private TeacherRepository teacherRepository;

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private CourseSelectionRepository courseSelectionRepository;

    @Autowired
    private StudentRepository studentRepository;

    @Override
    public Teacher getTeacherByUserId(Integer userId) {
        Teacher teacher = teacherRepository.findByUserId(userId);

        // 为新字段设置默认值（如果为null）
        if (teacher != null) {
            if (teacher.getEmail() == null) {
                teacher.setEmail("");
            }
            if (teacher.getPhone() == null) {
                teacher.setPhone("");
            }
            if (teacher.getOffice() == null) {
                teacher.setOffice("");
            }
            if (teacher.getBio() == null) {
                teacher.setBio("");
            }
            if (teacher.getAvatar() == null) {
                teacher.setAvatar("/images/default-avatar.svg");
            }
        }

        return teacher;
    }

    @Override
    public List<Course> getTeacherCourses(String teacherId) {
        List<Course> courses = courseRepository.findByTeacherId(teacherId);

        // 为每门课程设置学生数量
        for (Course course : courses) {
            int studentCount = getStudentCountForCourse(course.getCourseId());
            course.setStudentCount(studentCount);
        }

        return courses;
    }

    @Override
    public Map<String, Object> getTeachingOverview(String teacherId) {
        Map<String, Object> overview = new HashMap<>();

        // 获取教师课程数量
        List<Course> courses = courseRepository.findByTeacherId(teacherId);
        int courseCount = courses.size();

        // 获取该教师所有课程的学生总数
        int studentCount = courseSelectionRepository.countStudentsByTeacherId(teacherId);

        // 假设每门课每周4课时，计算本周课时数
        int weeklyHours = courseCount * 4;

        overview.put("courseCount", courseCount);
        overview.put("studentCount", studentCount);
        overview.put("weeklyHours", weeklyHours);

        return overview;
    }

    @Override
    public Course getCourseById(String courseId) {
        return courseRepository.findById(courseId).orElse(null);
    }

    @Override
    public int getStudentCountForCourse(String courseId) {
        return courseSelectionRepository.countByCourseId(courseId);
    }

    @Override
    public boolean updateCourse(String courseId, Course updatedCourse) {
        try {
            Course existingCourse = courseRepository.findById(courseId).orElse(null);
            if (existingCourse == null) {
                return false;
            }

            // 保持不变的字段
            updatedCourse.setCourseId(existingCourse.getCourseId());
            updatedCourse.setTeacherId(existingCourse.getTeacherId());

            // 确保必要字段不为null
            if (updatedCourse.getClassroomId() == null) {
                updatedCourse.setClassroomId(existingCourse.getClassroomId());
            }
            if (updatedCourse.getPeriodId() == null) {
                updatedCourse.setPeriodId(existingCourse.getPeriodId());
            }
            if (updatedCourse.getYear() == null) {
                updatedCourse.setYear(existingCourse.getYear());
            }
            // 保存更新之前检查时间字段
            if (updatedCourse.getStartTime() == null) {
                updatedCourse.setStartTime(existingCourse.getStartTime());
            }
            if (updatedCourse.getEndTime() == null) {
                updatedCourse.setEndTime(existingCourse.getEndTime());
            }

            // 保存更新
            courseRepository.save(updatedCourse);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean deleteCourse(String courseId) {
        try {
            // 先删除相关的选课记录
            courseSelectionRepository.deleteByCourseId(courseId);

            // 然后删除课程
            courseRepository.deleteById(courseId);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<Map<String, Object>> getTeacherStudents(String teacherId) {
        List<Map<String, Object>> result = new ArrayList<>();

        // 获取教师所有课程
        List<Course> courses = courseRepository.findByTeacherId(teacherId);

        // 对每门课程，获取选课的学生
        for (Course course : courses) {
            List<CourseSelection> selections = courseSelectionRepository.findByCourseId(course.getCourseId());

            for (CourseSelection selection : selections) {
                Map<String, Object> studentInfo = new HashMap<>();

                // 添加课程信息
                studentInfo.put("courseId", course.getCourseId());
                studentInfo.put("courseName", course.getName());

                // 获取学生信息
                studentRepository.findById(selection.getStudentId()).ifPresent(student -> {
                    studentInfo.put("studentId", student.getStudentId());
                    studentInfo.put("name", student.getName());
                    studentInfo.put("gender", student.getGender());
                    studentInfo.put("major", student.getMajor());
                    studentInfo.put("className", student.getGrade() + " " + student.getMajor());
                });

                // 添加选课状态
                studentInfo.put("status", selection.getStatus());

                result.add(studentInfo);
            }
        }

        return result;
    }

    @Override
    public List<Map<String, Object>> getTeacherGrades(String teacherId) {
        List<Map<String, Object>> result = new ArrayList<>();

        // 获取教师所有课程
        List<Course> courses = courseRepository.findByTeacherId(teacherId);

        // 对每门课程，获取选课记录
        for (Course course : courses) {
            List<CourseSelection> selections = courseSelectionRepository.findByCourseId(course.getCourseId());

            for (CourseSelection selection : selections) {
                Map<String, Object> gradeInfo = new HashMap<>();

                // 设置成绩记录ID和基本信息
                gradeInfo.put("id", selection.getSelectionId());
                gradeInfo.put("courseId", course.getCourseId());
                gradeInfo.put("courseName", course.getName());

                // 设置默认成绩类型为期末考试
                gradeInfo.put("type", "final");
                gradeInfo.put("typeDesc", "期末考试");
                gradeInfo.put("maxScore", 100);
                gradeInfo.put("weight", 100);

                // 获取学生信息
                studentRepository.findById(selection.getStudentId()).ifPresent(student -> {
                    gradeInfo.put("studentId", student.getStudentId());
                    gradeInfo.put("studentName", student.getName());
                });

                // 添加分数信息
                gradeInfo.put("score", selection.getScore());

                result.add(gradeInfo);
            }
        }

        return result;
    }

    @Override
    public Map<String, Object> getStudentDetail(String studentId, String teacherId) {
        // 检查学生是否存在
        if (!studentRepository.existsById(studentId)) {
            return null;
        }

        Map<String, Object> result = new HashMap<>();

        // 获取学生基本信息
        studentRepository.findById(studentId).ifPresent(student -> {
            Map<String, Object> studentInfo = new HashMap<>();
            studentInfo.put("studentId", student.getStudentId());
            studentInfo.put("name", student.getName());
            studentInfo.put("gender", student.getGender());
            studentInfo.put("major", student.getMajor());
            studentInfo.put("grade", student.getGrade());
            studentInfo.put("className", student.getGrade() + " " + student.getMajor());
            studentInfo.put("birthDate", student.getBirthDate());
            studentInfo.put("enrollmentDate", student.getEnrollmentDate());

            result.put("student", studentInfo);
        });

        // 获取该教师的课程
        List<Course> teacherCourses = courseRepository.findByTeacherId(teacherId);
        List<String> teacherCourseIds = teacherCourses.stream()
                .map(Course::getCourseId)
                .collect(Collectors.toList());

        // 获取学生选修的该教师的课程
        List<CourseSelection> selections = courseSelectionRepository.findByStudentId(studentId);
        List<Map<String, Object>> studentCourses = new ArrayList<>();

        for (CourseSelection selection : selections) {
            // 只处理该教师的课程
            if (teacherCourseIds.contains(selection.getCourseId())) {
                Map<String, Object> courseInfo = new HashMap<>();
                courseInfo.put("selectionId", selection.getSelectionId());
                courseInfo.put("courseId", selection.getCourseId());
                courseInfo.put("status", selection.getStatus());
                courseInfo.put("score", selection.getScore());
                courseInfo.put("semester", selection.getSemester());
                courseInfo.put("year", selection.getYear());

                // 添加课程详细信息
                courseRepository.findById(selection.getCourseId()).ifPresent(course -> {
                    courseInfo.put("courseName", course.getName());
                    courseInfo.put("credit", course.getCredit());
                    courseInfo.put("totalHours", course.getTotalHours());
                    courseInfo.put("courseType", course.getCourseType());
                    courseInfo.put("classDay", course.getClassDay());
                });

                studentCourses.add(courseInfo);
            }
        }

        result.put("courses", studentCourses);

        return result;
    }

    @Override
    public Map<String, Object> getStudentCourseGrade(String studentId, String courseId) {
        Map<String, Object> result = new HashMap<>();

        // 获取学生信息
        if (!studentRepository.existsById(studentId)) {
            return null;
        }

        studentRepository.findById(studentId).ifPresent(student -> {
            Map<String, Object> studentInfo = new HashMap<>();
            studentInfo.put("studentId", student.getStudentId());
            studentInfo.put("name", student.getName());
            studentInfo.put("gender", student.getGender());
            studentInfo.put("major", student.getMajor());
            studentInfo.put("grade", student.getGrade());
            studentInfo.put("className", student.getGrade() + " " + student.getMajor());

            result.put("student", studentInfo);
        });

        // 获取选课信息
        List<CourseSelection> selections = courseSelectionRepository.findByStudentId(studentId);
        CourseSelection targetSelection = null;

        for (CourseSelection selection : selections) {
            if (selection.getCourseId().equals(courseId)) {
                targetSelection = selection;
                break;
            }
        }

        if (targetSelection == null) {
            return null;
        }

        Map<String, Object> selectionInfo = new HashMap<>();
        selectionInfo.put("selectionId", targetSelection.getSelectionId());
        selectionInfo.put("courseId", targetSelection.getCourseId());
        selectionInfo.put("studentId", targetSelection.getStudentId());
        selectionInfo.put("status", targetSelection.getStatus());
        selectionInfo.put("score", targetSelection.getScore());
        selectionInfo.put("year", targetSelection.getYear());
        selectionInfo.put("semester", targetSelection.getSemester());

        // 假设的成绩细分（可根据需要扩展）
        List<Map<String, Object>> gradeComponents = new ArrayList<>();

        // 添加期末考试成绩组件
        Map<String, Object> finalExam = new HashMap<>();
        finalExam.put("name", "期末考试");
        finalExam.put("weight", 70);
        finalExam.put("score", targetSelection.getScore());
        finalExam.put("maxScore", 100);
        gradeComponents.add(finalExam);

        // 添加平时成绩组件（示例）
        Map<String, Object> usualGrade = new HashMap<>();
        usualGrade.put("name", "平时成绩");
        usualGrade.put("weight", 30);
        usualGrade.put("score", null);
        usualGrade.put("maxScore", 100);
        gradeComponents.add(usualGrade);

        selectionInfo.put("gradeComponents", gradeComponents);
        result.put("selection", selectionInfo);

        return result;
    }
}